Component({
  properties: {
    // 初始位置
    initTop: {
      type: Number,
      value: 300
    },
    initLeft: {
      type: Number,
      value: 0
    }
  },

  data: {
    left: 0,
    top: 0,
    windowWidth: 375,
    startX: 0,
    startY: 0,
    isMoving: false
  },

  lifetimes: {
    attached() {
      const systemInfo = wx.getSystemInfoSync()
      this.setData({
        windowWidth: systemInfo.windowWidth,
        left: this.properties.initLeft,
        top: systemInfo.windowHeight - this.properties.initTop
      })
    }
  },

  methods: {
    handleTouchStart(e) {
      const touch = e.touches[0]
	  console.log('handleTouchStart')
      this.setData({
        startX: touch.clientX,
        startY: touch.clientY,
        isMoving: true
      })
    },

    handleTouchMove(e) {
		console.log('handleTouchMove')
      if (!this.data.isMoving) return
      
      const touch = e.touches[0]
      const deltaX = touch.clientX - this.data.startX
      const deltaY = touch.clientY - this.data.startY
      
      this.setData({
        left: this.data.left + deltaX,
        top: this.data.top + deltaY,
        startX: touch.clientX,
        startY: touch.clientY
      })
    },

    handleTouchEnd() {
		console.log('handleTouchEnd')
      this.setData({ isMoving: false })
      this.adjustPosition()
    },

    adjustPosition() {
		console.log('adjustPosition')
      const { windowWidth } = this.data
      const centerX = this.data.left + 20 // 半宽30rpx（60rpx/2）
      const threshold = windowWidth / 2

      const newLeft = centerX > threshold 
        ? windowWidth - 40  // 贴右
        : 0  // 贴左
		console.log(newLeft)
      this.setData({
        left: newLeft,
        top: Math.min(
          Math.max(this.data.top, 0), 
          wx.getSystemInfoSync().windowHeight - 40
        )
      })
    }
  }
})